﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Smart.Service
{
    /// <summary>
    /// XML服务请求对象
    /// 根节点默认为 request
    /// </summary>
    public class XmlServiceRequest : IServiceRequest
    {
        public XmlServiceRequest()
        {
            Root = new XElement("request");
        }

        public XmlServiceRequest(XElement root)
        {
            Root = root;
        }

        public XElement Root { get; protected set; }

        public bool Contains(string key)
        {
            return Root.Element(key) != null;
        }

        public virtual string ToXmlString()
        {
            return Root.ToString();
        }

        /// <summary>
        /// 命名参数
        /// 获取时未包含指定Key的情况下返回NULL
        /// 设置时已包含指定Key为替换，未包含为添加
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string this[string key]
        {
            get
            {
                if (Contains(key))
                    return Root.Element(key).Value;
                return null;
            }
            set
            {
                if (Contains(key))
                    Root.Element(key).SetValue(value);
                else
                    Root.Add(new XElement(key, value));
            }
        }

        /// <summary>
        /// 请求对象简单克隆
        /// </summary>
        /// <returns></returns>
        public IServiceRequest Clone()
        {
            XmlServiceRequest request = new XmlServiceRequest();
            foreach (var x in Root.Elements())
            {
                request[x.Name.ToString()] = x.Value;
            }

            return request;
        }
    }
}
